package org.fengfei.wanmonitor;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class InternetUtil {

	private final static Pattern IP_REGEX = Pattern.compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))");

	private final static int TIMEOUT = 3000;

	public static boolean isNetworkAvailable() {
		boolean result = false;
		HttpURLConnection httpUrl = null;
		try {
			httpUrl = (HttpURLConnection) new URL("http://www.baidu.com").openConnection();
			httpUrl.setRequestMethod("HEAD");
			httpUrl.setConnectTimeout(TIMEOUT);
			httpUrl.connect();
			result = true;
		} catch (IOException e) {
		} finally {
			if (null != httpUrl) {
				httpUrl.disconnect();
			}
			httpUrl = null;
		}
		return result;
	}

	public static String getIPByDomain(String domain) {
		try {
			InetAddress myServer = InetAddress.getByName(domain);
			return myServer.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String getInternetIp() {
		String[] urls = {
				//
				"http://www.3322.org/dyndns/getip",
				//
				"http://city.ip138.com/ip2city.asp",
				//
				"http://2017.ip138.com/ic.asp",
				//
				"http://pv.sohu.com/cityjson?ie=utf-8"
				//
		};
		for (String url : urls) {
			try {
				String content = getContent(url);
				Matcher m = IP_REGEX.matcher(content);
				if (m.find()) {
					return m.group();
				}
			} catch (Exception e) {
			}
		}
		return null;
	}

	public static String getContent(String url) throws IOException {
		HttpURLConnection httpUrl = null;
		try {
			httpUrl = (HttpURLConnection) new URL(url).openConnection();
			httpUrl.setConnectTimeout(TIMEOUT);
			httpUrl.setUseCaches(false);
			httpUrl.connect();
			return inputStream2String(httpUrl.getInputStream());
		} catch (IOException e) {
			throw e;
		} finally {
			if (null != httpUrl) {
				httpUrl.disconnect();
			}
		}
	}

	private static String inputStream2String(InputStream in) throws IOException {
		StringBuilder out = new StringBuilder();
		byte[] b = new byte[1024];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}

}